<template>
    <div class="page">
        <h2 class="title">承运合同审批</h2>

        <div class="search">
            <div class="row">
                <label>合同标题：</label>
                <input v-model="q.contractTitle" placeholder="请输入合同标题" />
                <label>承运单位：</label>
                <input v-model="q.unitName" placeholder="请输入承运单位" />
                <label>承运负责人：</label>
                <input v-model="q.representative" placeholder="请输入承运负责人" />
            </div>
            <div class="row">
                <label>经办人：</label>
                <input v-model="q.handler" placeholder="请输入经办人" />
                <label>签订时间：</label>
                <input type="date" v-model="q.signingStart" />
                <span> - </span>
                <input type="date" v-model="q.signingEnd" />
                <button class="btn primary" @click="search">查询</button>
                <button class="btn" @click="reset">重置</button>
            </div>
        </div>

        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <tr>
                        <th>合同编号</th>
                        <th>合同标题</th>
                        <th>承运单位</th>
                        <th>承运负责人</th>
                        <th>线路</th>
                        <th>吨运价</th>
                        <th>包车条件吨位</th>
                        <th>包车金额</th>
                        <th>签订日期</th>
                        <th>经办人</th>
                        <th>创建时间</th>
                        <th>状态</th>
                        <th>审批人</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-if="loading">
                        <td :colspan="14" style="text-align:center">加载中...</td>
                    </tr>
                    <tr v-else-if="rows.length === 0">
                        <td :colspan="14" style="text-align:center">暂无数据</td>
                    </tr>
                    <tr v-for="r in rows" :key="r.id">
                        <td>{{ r.contractNumber }}</td>
                        <td>{{ r.contractTitle }}</td>
                        <td>{{ r.unitName }}</td>
                        <td>{{ r.carriageRepresentative }}</td>
                        <td>{{ r.routeName }}</td>
                        <td>{{ r.tonFreightRate }}</td>
                        <td>{{ r.charterConditionTonnage }}</td>
                        <td>{{ r.charterAmount }}</td>
                        <td>{{ r.signingDate }}</td>
                        <td>{{ r.handler }}</td>
                        <td>{{ r.createdAt }}</td>
                        <td>{{ r.status }}</td>
                        <td>{{ r.approver || '-' }}</td>
                        <td>
                            <a href="javascript:void(0)" @click="view(r)">查看</a>
                            &nbsp;|&nbsp;
                            <a href="javascript:void(0)" @click="approve(r)">通过</a>
                            &nbsp;|&nbsp;
                            <a href="javascript:void(0)" @click="reject(r)">拒绝</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="pagination" v-if="total > 0">
            <span>共{{ totalPage }}页/{{ total }}条数据</span>
            <button :disabled="page === 1" @click="goto(page - 1)">‹</button>
            <button v-for="p in pagesToShow" :key="p" :class="{ active: p === page }" @click="goto(p)">{{ p }}</button>
            <button :disabled="page >= totalPage" @click="goto(page + 1)">›</button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import { read, write } from '@/assets/Axios/axiosH'

const router = useRouter()
const counts = useCounterStore()

const q = reactive({ contractTitle: '', unitName: '', representative: '', handler: '', signingStart: '', signingEnd: '', status: '' })
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const totalPage = ref(0)
const rows = ref<any[]>([])
const loading = ref(false)

const pagesToShow = computed(() => {
    const max = Math.max(totalPage.value, 1)
    const cur = Math.min(Math.max(page.value, 1), max)
    const arr: number[] = []
    const start = Math.max(1, cur - 2)
    const end = Math.min(max, cur + 2)
    for (let i = start; i <= end; i++) arr.push(i)
    return arr
})

async function fetchList() {
    loading.value = true
    try {
        const params = new URLSearchParams()
        params.append('PageIndex', String(page.value))
        params.append('PageSize', String(pageSize.value))
        if (q.contractTitle) params.append('ContractTitle', q.contractTitle)
        if (q.unitName) params.append('UnitName', q.unitName)
        if (q.representative) params.append('CarriageRepresentative', q.representative)
        if (q.handler) params.append('Handler', q.handler)
        if (q.signingStart) params.append('SigningDate', q.signingStart)
        if (q.status) params.append('ApprovalStatus', q.status)
        params.append('t', String(Date.now()))
        const url = `contractmanagementread/api/ContractManagementControllers/GetCarriageContracts/Carriage`
        const res = await read.get(url, { params })
        const json: any = res?.data ?? {}
        const container = json?.data || {}
        total.value = Number(container?.TotalCount || 0)
        totalPage.value = Number(container?.TotalPage || 0)
        rows.value = Array.isArray(container?.data) ? container.data : []
    } catch (e) { console.error(e); rows.value = []; total.value = 0; totalPage.value = 0 }
    finally { loading.value = false }
}

function search() { page.value = 1; fetchList() }
function reset() { Object.assign(q, { contractTitle: '', unitName: '', representative: '', handler: '', signingStart: '', signingEnd: '', status: '' }); fetchList() }
function goto(p: number) { if (p < 1 || p > totalPage.value) return; page.value = p; fetchList() }

function view(r: any) { router.push(`/UpdateCarriageContracts?id=${encodeURIComponent(r.id)}`) }
async function approve(r: any) {
    if (!confirm('确认通过？')) return
    try {
        const payload = { id: r.id, approve: true, approvedBy: counts.Logins.Nickname || counts.Logins.Account || '' }
        const candidates = [
            'contractmanagementwrite/api/ContractManagement/ApproveCarriage/carriage/approve',
            'contractmanagementwrite/api/ContractManagement/Approve/approve'
        ]
        for (const u of candidates) {
            try {
                const res = await write.post(u, payload)
                const d = res?.data ?? {}
                if (res.status === 200 && (Number(d?.code) === 200 || d?.ok === true || d?.data === true)) { fetchList(); return }
            } catch { }
        }
        alert('审批失败，请重试')
    } catch (e) { console.error(e); alert('审批失败，请重试') }
}
async function reject(r: any) {
    if (!confirm('确认拒绝？')) return
    try {
        const payload = { id: r.id, approve: false, approvedBy: counts.Logins.Nickname || counts.Logins.Account || '' }
        const candidates = [
            'contractmanagementwrite/api/ContractManagement/RejectCarriage/carriage/reject',
            'contractmanagementwrite/api/ContractManagement/Reject/reject'
        ]
        for (const u of candidates) {
            try {
                const res = await write.post(u, payload)
                const d = res?.data ?? {}
                if (res.status === 200 && (Number(d?.code) === 200 || d?.ok === true || d?.data === true)) { fetchList(); return }
            } catch { }
        }
        alert('拒绝失败，请重试')
    } catch (e) { console.error(e); alert('拒绝失败，请重试') }
}

onMounted(() => { fetchList() })
</script>

<style scoped>
.page {
    padding: 16px
}

.title {
    font-size: 18px;
    margin-bottom: 12px
}

.search {
    background: #f7f7f7;
    padding: 12px;
    border-radius: 6px;
    margin-bottom: 12px
}

.row {
    display: flex;
    gap: 8px;
    align-items: center
}

.table {
    width: 100%;
    border-collapse: collapse
}

.table th,
.table td {
    border: 1px solid #eee;
    padding: 8px
}

.pagination {
    margin-top: 12px;
    display: flex;
    gap: 12px;
    align-items: center
}

.tab {
    padding: 8px 12px;
    border: 1px solid #eee;
    background: #fff;
    margin-right: 8px;
    cursor: pointer
}

.tab.active {
    background: #f0f0f0;
    border-bottom: 2px solid #1677ff
}
</style>
